<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="100px"

    >
      <el-form-item label="耗材" prop="code">
        <el-select
          v-model="formData.code"
          placeholder="请选择"
          ref="select"
          popper-class="select-popper"
          @change="selectItem"
        >
          <el-option
            v-for="item in List"
            :key="item.id"
            :value="item.code"
            :label="item.name"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="出库数量" prop="outNum">
        <el-input v-model="formData.outNum" placeholder="请输入出库数量" :disabled="numDisabled"
        />
      </el-form-item>
      <el-form-item label="出库时间" prop="outTime">
        <el-date-picker
          v-model="formData.outTime"
          type="datetime"
          placeholder="请选择出库时间"
          format="YYYY-MM-DD hh:mm:ss"
          value-format="YYYY-MM-DD hh:mm:ss"
          style="width: 100% !important;"
        />
      </el-form-item>
      <el-form-item label="负责人" prop="user">
        <el-input v-model="formData.user" placeholder="请输入负责人"/>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="formData.remark" placeholder="请输入备注"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import {DICT_TYPE, getIntDictOptions} from '@/utils/dict'
import {CommonStatusEnum} from '@/utils/constants'
import * as RoleApi from '@/api/system/role'
import * as OutApi from '@/api/consumable/out'
import * as InfoApi from '@/api/consumable/info'
import {list} from "postcss";

defineOptions({name: 'SystemRoleForm'})

const {t} = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const List = ref([])
const numDisabled = ref(false)
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const infoParams = reactive({
  pageNo: 1,
  pageSize: 10,
})
let dropdownWrap = null;
const formData = ref({
  id: undefined,
  code: "",
  outNum: "",
  outTime: "",
  user: "",
  remark: "",

})
const formRules: any = reactive({
  code: [{required: true, message: '耗材编号不能为空', trigger: 'blur'}],
  outNum: [{required: true, message: '出库数量不能为空', trigger: 'change'}],
  outTime: [{required: true, message: '出库时间不能为空', trigger: 'change'}],
  user: [{required: true, message: '负责人不能为空', trigger: 'change'}],
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  numDisabled.value = false
  getInfoList()

  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    numDisabled.value = true
    try {
      const data = await OutApi.getOut(id)
      formData.value = data.result
    } finally {
      formLoading.value = false
    }
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    code: "",
    outNum: "",
    outTime: "",
    user: "",
    remark: "",
  }
  formRef.value?.resetFields()

}
defineExpose({open}) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as RoleApi.RoleVO
    if (formType.value === 'create') {
      await OutApi.addOut(data)
      message.success(t('common.createSuccess'))
    } else {
      await OutApi.updateOut(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

const selectItem = (e) => {
  console.log(e)
}

const getInfoList = async () => {
  try {
    const data = await InfoApi.getInfoPage(infoParams)
    List.value = data.result
  } finally {
  }
}


const handleScroll = () => {
    if (dropdownWrap) {
      const {scrollTop, scrollHeight, clientHeight} = dropdownWrap;
      if (scrollTop + clientHeight >= scrollHeight) {
        // 滚动条到达底部的处理逻辑，例如加载更多数据
        infoParams.pageSize += 10
        getInfoList()
      }
    }
  }
;
const updateDropdownWrap = () => {
  dropdownWrap = document.querySelector('.select-popper .el-select-dropdown__wrap');
  if (dropdownWrap) {
    dropdownWrap.addEventListener('scroll', handleScroll);
  }
};

onMounted(() => {
  nextTick(() => {
    updateDropdownWrap();
  });
})
onBeforeUnmount(() => {
  if (dropdownWrap) {
    dropdownWrap.removeEventListener('scroll', handleScroll);
  }
});

</script>
